package com.cartoonrabbit.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.cartoonrabbit.config.exception.ServiceException;
import com.cartoonrabbit.config.minio.MinioProperties;
import com.cartoonrabbit.config.minio.MinioUtils;
import com.cartoonrabbit.consts.WxAPIURL;
import com.cartoonrabbit.service.IQRCodeService;
import com.cartoonrabbit.vo.RespBean;
import com.cartoonrabbit.wxapp.properties.WxAppInfoProperties;
import com.cartoonrabbit.wxapp.utils.ImageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

@Service
public class QRcodeServiceImpl implements IQRCodeService {

    @Autowired
    private WxAppInfoProperties wxAppInfoProperties;
    @Autowired
    private MinioProperties minioProperties;
    @Autowired
    private MinioUtils minioUtils;
    @Value("${wxapp.appinfo.env_version}")
    private String envVersion;

    /**
     * 获取小程序码
     * @param openId
     * @return
     */
    @Override
    public RespBean getUnlimitedQRCode(String openId) {
        String access_token = createAccessToken();
        if (ObjectUtils.isEmpty(access_token)){
            return RespBean.fail(500,"服务器异常");
        }
        // 获取小程序二维码
//        HttpRequest post = HttpUtil.createPost(String.format(WxAPIURL.WXACIODEUNLIMIT, access_token));
        String url=String.format(WxAPIURL.WXACIODEUNLIMIT, access_token);
        JSONObject data = new JSONObject();
        data.put("page","subpkg/login/login");
        // 生成特定的参数
        data.put("scene",openId);
        data.put("check_path",false);
        data.put("auto_color",true);
//        35, 180, 237
//        正式版为 "release"，体验版为 "trial"，开发版为 "develop"。默认是正式版。
        data.put("env_version",envVersion);
        String qrCodeImgUrl = createQrCodeImgUrl(url, data);
        return RespBean.success("SUCCESS",qrCodeImgUrl);
    }

    private String createAccessToken() {
        HttpRequest get = HttpUtil.createGet(String.format(WxAPIURL.ACCESSTOKEN,
                wxAppInfoProperties.getAppId(),wxAppInfoProperties.getAppSecret()));
        HttpResponse execute = get.execute();
        String body = execute.body();
        JSONObject entries = JSONUtil.parseObj(body);
        if (ObjectUtils.isEmpty(entries.get("access_token"))){
            return null;
        }
        // 获取access_token
        String access_token = entries.getStr("access_token");
        return access_token;
    }


    public String createQrCodeImgUrl(String url, JSONObject datas) {

        String qrCodeUrl = "";

        PrintWriter out = null;
        InputStream in = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数,利用connection的输出流，去写数据到connection中，我的参数数据流出我的电脑内存到connection中，让connection把参数帮我传到URL中去请求。
            out.print(datas);
            // flush输出流的缓冲
            out.flush();
            //获取URL的connection中的输入流，这个输入流就是我请求的url返回的数据,返回的数据在这个输入流中，流入我内存，我将从此流中读取数据。
            in = conn.getInputStream();
            // 生成图片
            try {
                CommonsMultipartFile multipartFile = ImageUtils.createMultipartFile(in, RandomUtil.randomString(10) + ".png");
                List<String> upload = minioUtils.upload(new MultipartFile[]{multipartFile}, minioProperties.getBucketName());
                return minioProperties.getEndpoint()+"/"+upload.get(0);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            //Base64转byte[]数组
        } catch (Exception e) {
            throw new ServiceException("请求异常",500);
        }
        return null;
    }



}
